package org.winexpress

import grails.converters.JSON
import org.codehaus.groovy.grails.web.json.JSONObject
import org.codehaus.groovy.grails.web.json.JSONArray

class ProductController {
    // shared methods
    def sendResponse(statusCode) {
        if (statusCode == 404) {
            JSONObject o = new JSONObject()
            o.put(statusCode, true)
            render o as JSON
        }
        
        response.status = statusCode
        render response
        
        // 200-OK (e.g. GET success)
        // 201-Created (e.g. POST success)
        // 403-Forbidden (e.g. LOGIN failure)
        // 400-Bad Request (e.g. PUT,POST,DELETE failure)
        // 404-Not Found (e.g. GET failure)
        // 500-Internal Server Error (other...)
    }
    
    
    // REST operations
    // GET
    def showSearch = {
        println 'ProductController Search >> Show >> START'
        
//        JSONObject o = request.JSON
        
//        ProductManagement pman = new ProductManagement()
//        ArrayList<ProductOption> optionsList = products.productOptions.toList() -- This doesn't work
//        println "check here : " + optionsList
       
        
        def productName = params['productName']
        def productType = params['productType']
        def wineType = params['wineType']
        def wineVarietal =  params['wineVarietal']
        def wineRegion =params['wineRegion']
        def products = Product.findAll()
         def p = Product.list() 
         p.clear()
//        if (o.has("productType")) { productType = o.get("productType") }
//        if (o.has("wineType")) { wineType = o.get("wineType") }
//        if (o.has("wineVarietal")) { wineVarietal = o.get("wineVarietal") }
//        if (o.has("wineRegion")) { wineRegion = o.get("wineRegion") }
        
        
//        if (params.productType) {   
//            //
//        }
        
//        def products = pman.searchProducts()
        products.each() {
            if (it.productType.productTypeName.toUpperCase().contentEquals(  productType.toString().toUpperCase()))
            {
               // println it.productType.productTypeName
                p.add(it)
            }
            
            if (it.productName.toUpperCase().contentEquals(  productName.toString().toUpperCase()))
            {
               // println it.productType.productTypeName
                p.add(it)
            }
        }
//
//        if (options.size() > 0) {
//
//        }
        //println pOption
        render p as JSON
        sendResponse(200)
  //println  p
        //println 'Show ALL product by ID >> ' + p.id + " " + p    
        
        println 'ProductController Search >> Show >> END'
    }
    
    
    // GET
    def showAll = {
//        println 'ProductController ALL >> Show >> START'
        
        ProductManagement pman = new ProductManagement()
        //InventoryManagement iman = new InventoryManagement()
        
        if (params.id) {
            if (params.id.isInteger()) {
                if (Product.exists(params.id)) {    

                    def p = pman.getProductByID(params.id)
        //            def pOption = p.productOptions
        //            println "product option: " + pOption

                    JSONObject productObj = new JSONObject()
                    productObj.put("id",p.id)
                    productObj.put("productName",p.productName)
                    productObj.put("description",p.description)
                    productObj.put("imageUrl",p.imageUrl)
                    productObj.put("productType",p.productType)
                    productObj.put("size",p.size)
                    productObj.put("costPrice",p.costPrice)
                    productObj.put("sellingPrice",p.sellingPrice)
                    productObj.put("stockCount",p.stockCount)
                    render productObj as JSON
                    sendResponse(200)
                }
            }
            else {
                println "NOT INTEGER:: " + params.id
            }
            
//            println 'Show ALL product by ID >> ' + p.id + " " + p
        }
        else {
            def allP = pman.listProducts()
            if (allP.length() > 0) {
//                println 'Listing all ALL products >> ' + allP
                render allP as JSON
                sendResponse(200)
            }
            else {
                sendResponse(404)
            }      
        }
        
//        println 'ProductController ALL >> Show >> END'
    }
    
    // PUT
    def updateAll = {
        println 'ProductController Wine>> Update >> START'
        
        JSONObject o = request.JSON
        
        println o
        
        ProductManagement pman = new ProductManagement()
        ProductOptionManagement poman = new ProductOptionManagement()
        
        def p = pman.getProductByID(o.get("id"))
        if (o.has("productName")) { p.productName = o.get("productName"); println p.productName }
        if (o.has("description")) { p.description = o.get("description"); println p.description }
        if (o.has("imageUrl")) { p.imageUrl = o.get("imageUrl"); println p.imageUrl }
        if (o.has("size")) { p.size = o.get("size"); println p.size }
        if (o.has("costPrice")) { p.costPrice = o.get("costPrice"); println p.costPrice }
        if (o.has("sellingPrice")) { p.sellingPrice = o.get("sellingPrice"); println p.sellingPrice }
        if (o.has("stockCount")) { p.stockCount = o.get("stockCount"); println p.stockCount }
        
        def currentOptionList = poman.listProductOptionsByProductID(p.id.toString())
        ArrayList<ProductOption> updatedOptionList = new ArrayList<ProductOption>()
       
        switch(p.productType.productTypeName) {
            case "Wine":
                println 'WINE PTYPE'
                // WINE PRODUCTS
                // Note: all the names retrieved from select are string
                if (o.has("wineType")) {
                    println 'wine type'
                    
                    WineTypeManagement wtman = new WineTypeManagement()
                    
                    def wt = wtman.getWineTypeForDbByWineTypeName(o.get("wineType"))
                    int poID = 0;
                    currentOptionList.each() {
                        if (it.optionType.equals("wineType")) {
                            poID = it.id
                            println poID
                        }
                    }
                    def po = poman.getProductOptionByID(poID)
                    po.optionTypeId = wt.id
                    
                    updatedOptionList.add(po)
                    println 'size now: ' + updatedOptionList.size()
                }
                if (o.has("wineVarietal")) {
                    println 'wine wineVarietal'
                    
                    WineVarietalManagement wvman = new WineVarietalManagement()
                    
                    def wv = wvman.getWineVarietalForDbByWineVarietalName(o.get("wineVarietal"))
                    int poID = 0;
                    currentOptionList.each() {
                        if (it.optionType.equals("wineVarietal")) {
                            poID = it.id
                            println poID
                        }
                    }
                    def po = poman.getProductOptionByID(poID)
                    po.optionTypeId = wv.id
                    
                    updatedOptionList.add(po)
                    println 'size now: ' + updatedOptionList.size()
                }
                if (o.has("wineRegion")) {
                    println 'wine wineRegion'
                    
                    WineRegionManagement wrman = new WineRegionManagement()
                    
                    def wr = wrman.getWineRegionForDbByWineRegionName(o.get("wineRegion"))
                    int poID = 0;
                    currentOptionList.each() {
                        if (it.optionType.equals("wineRegion")) {
                            poID = it.id
                            println poID
                        }
                    }
                    def po = poman.getProductOptionByID(poID)
                    po.optionTypeId = wr.id
                    
                    updatedOptionList.add(po)
                    println 'size now: ' + updatedOptionList.size()
                }
                break
            case "Gift":
                if (o.has("giftType")) {
                    println 'giftType'
                    
//                    GiftTypeManagement gtman = new GiftTypeManagement()
                    
//                    def gt = gtman.getWineTypeForDbByWineTypeName(o.get("giftType"))
                    int poID = 0;
                    currentOptionList.each() {
                        if (it.optionType.equals("giftType")) {
                            poID = it.id
                            println poID
                        }
                    }
                    def po = poman.getProductOptionByID(poID)
//                    po.optionTypeId = gt.id
                    
                    updatedOptionList.add(po)
                    println 'size now: ' + updatedOptionList.size()
                }
                break
            case "Hamper":
                if (o.has("hamperType")) {
                    println 'hamperType'
                    
//                    HamperTypeManagement htman = new HamperTypeManagement()
//                    
//                    def ht = wtman.getWineTypeForDbByWineTypeName(o.get("hamperType"))
                    int poID = 0;
                    currentOptionList.each() {
                        if (it.optionType.equals("hamperType")) {
                            poID = it.id
                            println poID
                        }
                    }
                    def po = poman.getProductOptionByID(poID)
//                    po.optionTypeId = ht.id
                    
                    updatedOptionList.add(po)
                    println 'size now: ' + updatedOptionList.size()
                }
                break
        }
//        if (o.has("wineType")) {
//            updatedOptionList.each() {
//                if (it.optionType.equals(o.get("wineType"))) {
//                    println 'wine type'
//                    ProductOption po = new ProductOption()
//                    po.optionType = "wineType"
//                    WineTypeManagement wtman = new WineTypeManagement()
//                    def wt = wtman.getWineTypeForDbByWineTypeName(product.get("wineType"))
//                    po.optionTypeId = wt.id
//                    p.productOptions
//                }
//                
//                if (o.has("wineVarietal")) {
//                    currentOptionList.each() {
//                        if (it.optionType.equals(o.get("wineVarietal"))) {
//
//                        }
//                        print it
//                    }
//                }
//
//                if (o.has("wineRegion")) {
//                    currentOptionList.each() {
//                        if (it.optionType.equals(o.get("wineRegion"))) {
//
//                        }
//                        print it
//                    }
//                }
//            }
//        }
        
        def result = pman.updateProduct(p, updatedOptionList)
        if (result == true) {
            println 'ProductController Wine>> Update >> ' + result
            sendResponse(200)
        }
        else {
            println 'ProductController Wine>> Update >> ' + result
            sendResponse(400)
        }
        

        println 'ProductController Wine>> Update >> END'

    }
    
    // DELETE
    def deleteAll = {
        println 'ProductController Wine>> delete >> START'
        
        ProductManagement pman = new ProductManagement()
        
        if (params.id && Product.exists(params.id)) {    
            def result = pman.deleteProduct(id)
            
            if (result == true) {
                println 'ProductController Wine>> delete >> ' + result
                sendResponse(200)
            }
            else {
                println 'ProductController Wine>> delete >> ' + result
                sendResponse(400)
            }
        }
        
        println 'ProductController Wine>> delete >> END'
    }
    
    // POST
    def saveAll = {
        println 'ProductController Wine>> Save >> START'
        
        JSONObject o = request.JSON
        
        ProductManagement pman = new ProductManagement()
        
        def result = pman.addProduct(o)
        if (result == true) {
            println 'ProductController Wine>> Save >> ' + result
            sendResponse(201)
        }
        else {
            println 'ProductController Wine>> Save >> ' + result
            sendResponse(400)
        }
        
        println 'ProductController Wine>> Save >> END'
    }
    
    
    
    // supporting operations
    def isUniqueProductName(productName) {
        
        def status = false
        
        ProductManagement pman = new ProductManagement()
        Product p = null
        
        p = pman.getWineTypeForDbByWineTypeName(productName)
        
        if (p == null) {
            status = true 
        }
        
        return status
    }
    
}
